package com.i.template.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.i.template.constant.ResponseStatusEnum;
import com.i.template.domain.UserDO;
import com.i.template.exception.BusinessException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/7/25
 */
public class JWTUtils {
    private static final byte[] KEY = "lewis".getBytes();
    private static final DateField field = DateField.MONTH;
    public static String createToken(UserDO userDO){
        Long uid = userDO.getUid();
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        return generateToken(map,field,1);
    }
    public static String generateToken(Map<String, Object> payload, DateField dateField, int time){
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(dateField, time);

        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);

        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);

        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        return JWTUtil.createToken(payload, KEY);
    }
    public static JWTPayload parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        if(!jwt.setKey(KEY).verify()) {
            throw new BusinessException("token 异常", ResponseStatusEnum.TOKEN_AUTH_FAILED.getCode());
        }

        if(!jwt.validate(0)) {
            throw new BusinessException("token 已过期请重新登录",ResponseStatusEnum.TOKEN_AUTH_FAILED.getCode());
        }
        return jwt.getPayload();
    }
}
